#pragma once
#include <string>
#include <pthread.h>
#include <iostream>

namespace ThreadMoudle
{
    class ThreadData
    {
    public:
        ThreadData(const std::string &name, pthread_mutex_t *lock)
            :_name(name), _lock(lock)
        { }

        std::string Name()
        {
            return _name;
        }
    public:
        std::string _name;
        pthread_mutex_t *_lock;
    };

    // 线程要执行的方法
    // typedef void (*func_t)(const std::string &name); // 函数指针类型
    typedef void (*func_t)(ThreadData *td); // 函数指针类型

    class Thread
    {
    public:
        void Excute()
        {
            std::cout << _name << " is running" << std::endl;
            _isrunning = true;
            // _func(_name);
            _func(_td);
            _isrunning = false;
        }

    public:
        Thread(const std::string &name, func_t func, ThreadData *td)
            : _name(name), _func(func), _td(td)
        {
            std::cout << "create " << _name << " done" << std::endl;
        }

        // 这样定义会多出一个this，加上static就可以了
        static void *ThreadRoutine(void *args)
        {
            Thread *Self = static_cast<Thread *>(args);
            Self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0) return false;
            return true;
        }

        std::string Status()
        {
            if(_isrunning) return "running";
            else return "sleep";
        }

        void Stop()
        {
            ::pthread_cancel(_tid);
            _isrunning = false;
            std::cout << _name << " Stop" << std::endl;
        }

        void Join()
        {
            ::pthread_join(_tid, nullptr);
            std::cout << _name << " Joined" << std::endl;
            delete _td;
        }

        std::string Name()
        {
            return _name;
        }

        ~Thread()
        {
            // std::cout << "~Thread()" << std::endl;
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;

        ThreadData *_td;
    };
}